package com.dfkj.file.service.impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.ZipUtil;
import cn.hutool.http.HttpUtil;
import com.dfkj.file.mapper.FileMapper;
import com.dfkj.file.model.dto.post.DownLoadDto;
import com.dfkj.file.model.entity.ZipFile;
import com.dfkj.file.service.DownLoadService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

@Service
public class DownLoadServiceImpl implements DownLoadService {


    @Value("${upload.filepath}")
    private String filepath;

    @Resource
    private FileMapper fileMapper;

    @Override
    public void DownLoadFile(DownLoadDto dto) {

        List<String> urls = dto.getUrls();
        String fileSpf = UUID.fastUUID().toString();
        LocalDateTime time = LocalDateTime.now();
        DateTimeFormatter dtf2 = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        String strDate2 = dtf2.format(time);

        String local = StringUtils.join(strDate2, "/", fileSpf, ".zip");
        //所有下载完成后对文件夹中的文件进行打包
        //压缩到的文件夹位置
        ZipFile zipFile = new ZipFile();
        long id = RandomUtil.randomLong(12);
        zipFile.setFilePath(local);
        zipFile.setId(id);
        zipFile.setCreateTime(System.currentTimeMillis());
        zipFile.setState(0);
        //保存列表
        fileMapper.insert(zipFile);

        //异步任务
        ThreadUtil.execAsync(() -> {
        //下载数据
        for (String url : urls) {
            String fileName = url.substring(url.lastIndexOf("."));
            String uuidName = UUID.randomUUID().toString();
            String localPath = StringUtils.join(filepath, strDate2, "/", fileSpf, "/", uuidName, ".", fileName);
            File file = new File(localPath);
            File parentDir = file.getParentFile();
            if (!parentDir.exists() && !parentDir.mkdirs()) {
                throw new IllegalStateException("创建文件夹失败: " + parentDir);
            }
            HttpUtil.downloadFile(url, file);
        }
            //打包更新状态
            String sourcePath = StringUtils.join(filepath, strDate2, "/", fileSpf);
            String zipFilePath = StringUtils.join(filepath, local);
            File zip = ZipUtil.zip(sourcePath, zipFilePath, true);
            if (zip.exists()) {
                zipFile.setState(1);
                fileMapper.updateById(zipFile);
            }

        });


    }
}
